package cn.fbs.util;

import cn.fbs.util.imageshort.FileUtil;
import com.coremedia.iso.IsoFile;

import java.io.*;
import java.util.ArrayList;
//import org.bytedeco.javacv.FFmpegFrameGrabber;
//import org.bytedeco.javacv.Frame;
//import org.bytedeco.javacv.Java2DFrameConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;


@Component
public class VideoUtil {
    /**
     * 获取视频文件的播放长度(mp4、mov格式)
     * @param videoPath
     * @return 单位为毫秒
     */
    public static long getMp4Duration(String videoPath) throws IOException {
        IsoFile isoFile = new IsoFile(videoPath);
        long lengthInSeconds =
                isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
                        isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
        isoFile.close();
        return lengthInSeconds;
    }


    /**
     * 得到语音或视频文件时长,单位秒
     * @param filePath
     * @return
     * @throws IOException
     */
    public static long getDuration(String filePath) throws IOException {
        String format = getVideoFormat(filePath);
        long result = 0;
        if("wav".equals(format)){
            result = AudioUtil.getDuration(filePath).intValue();
        }else if("mp3".equals(format)){
            result = AudioUtil.getMp3Duration(filePath).intValue();
        }else if("m4a".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        }else if("mov".equals(format)){
            result = VideoUtil.getMp4Duration(filePath);
        }else if("mp4".equals(format)){
            result = VideoUtil.getMp4Duration(filePath);
        }

        return result;
    }

    /**
     * 得到语音或视频文件时长,单位秒
     * @param filePath
     * @return
     * @throws IOException
     */
    public static long getDuration(String filePath,String format) throws IOException {
        long result = 0;
        if("wav".equals(format)){
            result = AudioUtil.getDuration(filePath).intValue();
        }else if("mp3".equals(format)){
            result = AudioUtil.getMp3Duration(filePath).intValue();
        }else if("m4a".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        }else if("mov".equals(format)){
            result = VideoUtil.getMp4Duration(filePath);
        }else if("mp4".equals(format)){
            result = VideoUtil.getMp4Duration(filePath);
        }

        return result;
    }


    /**
     * 得到文件格式
     * @param path
     * @return
     */
    public static String getVideoFormat(String path){
        return  path.toLowerCase().substring(path.toLowerCase().lastIndexOf(".") + 1);
    }




    /**
     * 飞腾
     * @param filePath
     * @param compressRatio
     * @return
     * @throws Exception
     */
    public static String fetchFrame(String filePath,int compressRatio) throws Exception {
        String imagePath=filePath.substring(0,filePath.lastIndexOf("."))+".jpg";
        ArrayList<String> strings = new ArrayList<>();
        strings.add("ffmpeg");
        strings.add("-i");
        strings.add(filePath);
        strings.add(imagePath);
        strings.add("-ss");
        strings.add("00:00:02");
        strings.add("-r");
        strings.add("1");
        strings.add("-vframes");
        strings.add("-an");
        strings.add("-vcodec");
        strings.add("mjpeg");
        ProcessBuilder processBuilder = new ProcessBuilder(strings);
        processBuilder.start();
        String join = StringUtils.join(strings, " ");
        System.out.println(join);
        Thread.sleep(500);
        File file = new File(imagePath);
        String base64Str = FileUtil.getCompressBase64FromUrl(file, compressRatio);
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!\n"+base64Str);
        return base64Str;
    }


    /**
     * x86
     * @param filePath
     * @param compressRatio
     * @return
     * @throws Exception
     */
//    public static String fetchFrame(String filePath,int compressRatio) throws Exception {
//        FFmpegFrameGrabber fFmpegFrameGrabber = FFmpegFrameGrabber.createDefault(filePath);
//        fFmpegFrameGrabber.start();
//        int fflength = fFmpegFrameGrabber.getLengthInFrames();
//        int i = 0;
//        Frame frame = null;
//        String base64Str="";
//        while (i < fflength) {
//            frame = fFmpegFrameGrabber.grabFrame();
//            if ((i > 5) && (frame.image != null)) {
//                Java2DFrameConverter converter = new Java2DFrameConverter();
//                BufferedImage bufferedImage = converter.getBufferedImage(frame);
//                /**
//                 * 第二种方法没有flush，存在问题
//                 */
//
////                FileOutputStream fileOutputStream = new FileOutputStream(System.currentTimeMillis()+".jpg");
////                ImageIO.write(bufferedImage,"jpeg",fileOutputStream);
////                fileOutputStream.close();
//
////                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
////                ImageIO.write(bufferedImage,"png",byteArrayOutputStream);
////                byte[] bytes = byteArrayOutputStream.toByteArray();
//
//                base64Str = FileUtil.getCompressBase64FromUrl(bufferedImage, compressRatio);
//                bufferedImage.flush();
////                base64Str = Base64.getEncoder().encodeToString(bytes);
//                break;
//            }
//            i++;
//        }
//        fFmpegFrameGrabber.close();
//        return base64Str;
//    }

}
